package cn.main.dao.impl;

import cn.main.dao.BaseDao;
import cn.main.utils.DataUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Author: chengwei
 * Date:   2016/5/20
 * Time:   9:48
 */
@Repository
public class BaseDaoImpl implements BaseDao {
    @Resource
    private JdbcTemplate jdbcTemplate;
    
    @Resource
    private SessionFactory factory;

    public SessionFactory getFactory() {
        return factory;
    }

    public void setFactory(SessionFactory factory) {
        this.factory = factory;
    }

    Logger log = Logger.getLogger(this.getClass());

    @Override
    public Session getCurrentSession() {
        return factory.getCurrentSession();
    }

    @Override
    public Map<String, Object> queryForMap(String sql, Object... args) {
        log.info(String.format("执行sql:%s,参数:%s",sql, DataUtils.toString(args)));
        return jdbcTemplate.queryForMap(sql,args);
    }

    @Override
    public List<Map<String, Object>> queryForList(String sql, Object... args) {
        log.info(String.format("执行sql:%s,参数:%s",sql,DataUtils.toString(args)));
        return jdbcTemplate.queryForList(sql, args);
    }

    @Override
    public int execute(String sql, Object... args) {
        log.info(String.format("执行sql:%s,参数:%s",sql,DataUtils.toString(args)));
        return jdbcTemplate.update(sql,args);
    }

    @Override
    public int insert(String tableName, Map<String, Object> map) {
        if (map.size() == 0) {
            return 0;
        }
        List<Object> args = new ArrayList<>();
        StringBuilder sql = new StringBuilder("INSERT INTO ");
        sql.append(tableName);
        sql.append("(");
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            sql.append(key).append(",");
            args.add(map.get(key));
        }
        sql.deleteCharAt(sql.length()-1);
        sql.append(") VALUES (");
        for (String key : keySet) {
            sql.append("?,");
        }
        sql.deleteCharAt(sql.length()-1);
        sql.append(")");
        log.info(String.format("执行sql:%s,参数:%s",sql,DataUtils.toString(args)));
        return execute(sql.toString(),args);
    }

    @Override
    public int[] executeBatch(String sql, List<Object[]> args) {
        log.info(String.format("执行sql:%s,参数:%s",sql,DataUtils.toString(args)));
        return jdbcTemplate.batchUpdate(sql,args);
    }
}
